package com.ley.springboot.commons.reflect;

import lombok.NonNull;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author liuenyuan
 **/
public class ReflectUtils extends ReflectionUtils {

    /**
     * 获取父类的泛型
     *
     * @param subClass sub class
     * @return return super generic type
     **/
    public static <T> Class<T> getClassFromGenericType(@NonNull Class<?> subClass) {
        Object genericSuperclass = subClass.getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            //获取当前类的带有泛型的父类类型
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            //返回实际参数类型(泛型可以写多个)
            Type[] types = parameterizedType.getActualTypeArguments();
            if (types != null && types.length > 0) {
                Class<T> targetClass = (Class<T>) types[0];
                return targetClass;
            }
        }
        return null;
    }
}
